package textapp.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import textapp.connector.MessageCode;
import textapp.connector.ServerConnectorMessage;

import com.google.gson.Gson;

/**
 * Servlet implementation class GenericJsonServlet
 */
public abstract class GenericJsonServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GenericJsonServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		executeRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		executeRequest(request, response);
	}

	protected void executeRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Object ret = executeRequestJson(request, response);
			Gson gson = new Gson();
			
			//response.setContentType("application/json");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.print(gson.toJson(ret));		
				
		}catch(Throwable t) {
			t.printStackTrace();
			Gson gson = new Gson();
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.print(gson.toJson(new ServerConnectorMessage(MessageCode.FAIL)));					
		}
		
	}
	
	protected abstract Object executeRequestJson(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
	
}
